// index.js
const app = getApp();
var funcs = require('../../static/js/funcs.js');
import * as echarts from '../../components/ec-canvas/echarts.min';
const chartsOption = require('../../static/js/chartsOption')
import {
  cities,
  areas
} from '../../static/js/city';

Page({
  data: {
    yibiao_types:['折线图','扇形图'],
    select_type: '折线图',
    time_bar: ['天', '周', '月', '年', '自定义'],
    select_time: 0,
    period: '2024.01.01-2024.01.07',
    today: '',
    select_date: '',
    select_date_start: '',
    select_date_end: '',
    select_inst: "全部",
    proj_bar: ['存款', '贷款', '其他'],
    select_proj:'存款',
    ec: {
      lazyLoad: true
    },
    gender_bar: ['全部', '男士', '女士'],
    select_gender: 0,
    category_bar: [{
      name: '已预约',
      select: 1
    }, {
      name: '已完成',
      select: 0
    }, {
      name: '已逾期',
      select: 0
    }],
    xData: ['1月','2月','3月','4月'],
    yData: [[1,2,3],[2,3,4],[4,5,1]],
    cities,
    areas,
    city: "",
    area: "",
    multiIndex: [0, 0],
    objectMultiArray: [cities, areas[0]],
    networkList: [],
    inst_list:[],
    mapid_list:[]
  },
  agree(e){
    console.log("用户同意隐私授权, 接下来可以调用隐私协议中声明的隐私接口")
    //这里写入同意后需要执行的代码，一般不用写也行
  },
  disagree(e){
      console.log("用户拒绝隐私授权, 未同意过的隐私协议中的接口将不能调用")
      wx.exitMiniProgram()
  },
  select_type_button:function(e){
    let project = e.currentTarget.dataset.project;
    console.log("选中的仪表盘类型：" + project)
    this.setData({
      select_type: project
    })
  },
  pre_login: function (res) {
    return new Promise((resolve, reject) => {
      wx.login({
        success: res => {
          //发起网络请求console.log
          app.globalData.code = res.code;
          resolve(res)
        },
        fail(res) {
          reject(res);
        }
      })
    })
  },

  privacy(){
    let that = this
    wx.getPrivacySetting({
      success: res => {
        if (res.needAuthorization) {
          that.setData({
            showPrivacy:true
          })
          app.globalData.showPrivacy=true
          // this.seglobalData.showPrivacy=false
          console.log("needAuthorization")
        } else{
          that.setData({
            showPrivacy:false
          })
          app.globalData.showPrivacy=false
          // this.globalData.showPrivacy=ffalse
          console.log("not needAuthorization")
        }
      },
      fail: () => { },
      complete: () => { },
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // this.privacy()
    funcs.getaccessToken().then(res=>{
      if(res.data.succeed){
        console.log("accesstoken为：",res.data.data.accessToken)
      }
    })

    this.pre_login().then(res => {
      console.log("该用户的code为：" + res.code)
      funcs.getOpenid(res.code).then(res =>{
        if(res.data.succeed){
          console.log("该用户的openid为："+res.data.data.openid)
          app.globalData.openid = res.data.data.openid;
          console.log("设置全局openid为：>"+app.globalData.openid)
          let openid = app.globalData.openid
          funcs.judgeStaff(openid).then(res=>{
            if(res.data.succeed){
              console.log("该员工已注册")
              app.globalData.loginedFlag = true
              this.setData({
                loginedFlag: true
              })
            }else{
              app.globalData.loginedFlag = false
              this.setData({
                loginedFlag: false
              })
              wx.reLaunch({
                url: '/pages/my/my',
              })
              wx.showToast({
                title: "请先绑定",
                icon: 'none',
                duration: 2000
              })
            }
          })
        }else{
          console.log("获取用户openid错误")
        }
      })
    })

    console.log("onload 加载报表")
    let that = this;

    // 获取当前日期
    let date = new Date();
    let year = date.getFullYear();
    let month = (date.getMonth() + 1).toString().padStart(2, '0'); // 月份从0开始，需要加1
    let day = date.getDate().toString().padStart(2, '0');
    let today = year + "-" + month + "-" + day;
    this.setData({
      today: today,
      select_date: today
    })
    this.assembleData();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  select_inst_func:function(e){
    console.log(this.data.networkList)
    console.log('picker发送选择改变，携带值为', e.detail.value)
    let index = e.detail.value;
    this.setData({
      select_inst: this.data.inst_list[index]
    })
    this.onChange();
  },
  select_bus_func: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    let index = e.detail.value;
    this.setData({
      select_proj: this.data.proj_bar[index]
    })
    this.onChange();
  },
  //city选择
  bindCityChange(event) {
    console.log('picker发送选择改变，携带值为', event.detail.value)
    let city_index = event.detail.value[0];
    let area_index = event.detail.value[1];
    let city = this.data.cities[city_index].name;
    let area = this.data.objectMultiArray[1][area_index].name;
    
    funcs.getAllByAreaNameWithNot(city,area).then(res => {
      // console.log(res.data);
      let real_networkList = []
      let networkList = res.data.data;
      let mapidList = []
      let instList = []
      networkList.map((item, index) => {
        if (item.telephone != null && item.telephone.length > 0)
          real_networkList.push(item);
          instList.push(item.name)
          mapidList.push(item.map_id)
      })
      this.setData({
        networkList: real_networkList,
        inst_list: instList,
        mapid_list: mapidList,
        select_inst: "全部"
      })
    }).then(() => {
      this.setData({
        city: city,
        area: area,
        city_area: city + '-' + area
      })
      console.log(this.data.city)
      console.log(this.data.area)
    })
  },
  //city切换
  bindColumnCityChange(event) {
    console.log('修改的列为', event.detail.column, '，值为', event.detail.value);
    switch (event.detail.column) {
      case 0: //修改第一列
        let arr = this.data.multiIndex;
        arr[0] = event.detail.value;
        arr[1] = 0;
        this.setData({
          objectMultiArray: [cities, areas[event.detail.value]],
          multiIndex: arr,
        })
        break;
      case 1: //修改第二列
        let arr2 = this.data.multiIndex;
        arr2[1] = event.detail.value;
        // console.log(arr2)
        this.setData({
          multiIndex: arr2,
        })
        break;
    }
    // console.log(this.data.multiIndex)
  },

    // 改变时间类型
    select_time_func: function (e) {
      let index = e.currentTarget.dataset.index;
      let select_date = '';
      let select_date_start = '';
      let select_date_end = '';
      if (index == 0) { // 选今天
        select_date = this.data.today;
      } else if (index == 1) { // 选周，默认当前周
        let a = this.getWeekDates(this.data.today);
        select_date = a[0] + ' 至 ' + a[1];
      } else if (index == 2) { // 选月，默认当月
        select_date = this.data.today.slice(0, 7);
      } else if (index == 3) { // 选年，默认当年
        select_date = this.data.today.slice(0, 4);
      } else if (index == 4) { // 选自定义，默认当周
        let a = this.getWeekDates(this.data.today);
        select_date_start = a[0];
        select_date_end = this.data.today;
      }
      if (index != 4) { // 选自定义
        this.setData({
          select_time: index,
          select_date: select_date
        })
      } else { // 选其他
        this.setData({
          select_time: index,
          select_date_start: select_date_start,
          select_date_end: select_date_end
        })
      }
      this.onChange();
    },
   // 改变日期
   select_date_func: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value);
    let select_time = this.data.select_time;
    let select_date_tmp = e.detail.value;
    if (select_time == 1) { // 如果是周
      let a = this.getWeekDates(select_date_tmp);
      select_date_tmp = a[0] + ' 至 ' + a[1];
    }
    // 如果只是选一个日期
    if (select_time != 4) {
      this.setData({
        select_date: select_date_tmp
      })
      this.onChange();
      return;
    }
    // 如果是选两个日期
    let flag = e.currentTarget.dataset.flag;
    if (flag == 1) {
      let select_date_start = select_date_tmp;
      let select_date_end = this.data.select_date_end;
      let date1 = new Date(select_date_start);
      let date2 = new Date(select_date_end);
      if (date1 > date2) {
        this.setData({
          select_date_start: select_date_end,
          select_date_end: select_date_start
        })
      } else {
        this.setData({
          select_date_start: select_date_tmp
        })
      }
    } else {
      let select_date_start = this.data.select_date_start;
      let select_date_end = select_date_tmp;
      let date1 = new Date(select_date_start);
      let date2 = new Date(select_date_end);
      if (date1 > date2) {
        this.setData({
          select_date_start: select_date_end,
          select_date_end: select_date_start
        })
      } else {
        this.setData({
          select_date_end: select_date_tmp
        })
      }
    }

    this.onChange();
  },
    // 获取/刷新数据
  onChange: function () {
    let that = this;
    let time_type = that.data.select_time;
    let date1 = that.data.select_date;
    let date2 = '';
    if (time_type == 1) { // 如果是周
      date1 = that.data.select_date.slice(0, 10);
      date2 = that.data.select_date.slice(13);
    } else if (time_type == 4) { // 如果是自定义
      date1 = that.data.select_date_start;
      date2 = that.data.select_date_end;
    }
    // let inst = that.data.inst_bar[that.data.select_inst];
    // let project = that.data.proj_bar[that.data.select_proj];
    let gender = that.data.select_gender;
    let year = that.data.select_date.slice(0, 4);
    let month = that.data.select_date.slice(5, 7);

    if (gender == 0) {
      gender = 3;
    }
    //刷新数据
    // wx.request({
    //   url: 'url',
    // })
  },
   // 获取当前周的第一天和最后一天
   getWeekDates: function (date) {
    //获取所选时间的date
    const currentDate = new Date(date)
    //返回date是一周中的某一天
    const week = currentDate.getDay()
    //一天的毫秒数
    const millisecond = 1000 * 60 * 60 * 24
    //减去的天数
    const minusDay = week != 0 ? week - 1 : 6
    //本周 周一
    const monday = new Date(currentDate.getTime() - minusDay * millisecond)
    let year1 = monday.getFullYear();
    let month1 = (monday.getMonth() + 1).toString().padStart(2, '0'); // 月份从0开始，需要加1
    let day1 = monday.getDate().toString().padStart(2, '0');
    let mon = year1 + "-" + month1 + "-" + day1;

    //本周 周日
    const sunday = new Date(monday.getTime() + 6 * millisecond)
    let year2 = sunday.getFullYear();
    let month2 = (sunday.getMonth() + 1).toString().padStart(2, '0'); // 月份从0开始，需要加1
    let day2 = sunday.getDate().toString().padStart(2, '0');
    let sun = year2 + "-" + month2 + "-" + day2;

    // console.log(mon, sun);
    return [mon, sun]
  },
    // 改变性别
    select_gender_func: function (e) {
      let index = e.currentTarget.dataset.index;
      this.setData({
        select_gender: index
      })
      this.onChange();
    },
   // 改变人数类别
   select_cate_func: function (e) {
    let index = e.currentTarget.dataset.index;
    let category_bar_temp = this.data.category_bar;

    // 如果是取消按钮，检查是否全0
    if (category_bar_temp[index].select == 1) {
      let flag = 0; // 全0flag
      for (let i = 0; i < category_bar_temp.length; i++) {
        if (index == i) {
          continue;
        }
        if (category_bar_temp[i].select == 1) {
          flag = 1;
          break;
        }
      }
      // 如果是全零
      if (flag == 0) {
        // console.log('return')
        return;
      }
    }
    category_bar_temp[index].select = category_bar_temp[index].select == 1 ? 0 : 1;
    this.setData({
      category_bar: category_bar_temp
    })
    this.assembleData();
  },

  // 组装数据
  assembleData: function () {
    let chartData = {};
    chartData.xData = this.data.xData;
    let series = [];
    let booked = this.data.category_bar[0].select;
    let finished = this.data.category_bar[1].select;
    let dateout = this.data.category_bar[2].select;
    if (booked) {
      series.push({
        name: '预约人数',
        type: 'line',
        // smooth: true,
        data: this.data.yData[0]
      })
    }
    if (finished) {
      series.push({
        name: '核销人数',
        type: 'line',
        // smooth: true,
        data: this.data.yData[1]
      })
    }
    if (dateout) {
      series.push({
        name: '逾期人数',
        type: 'line',
        // smooth: true,
        data: this.data.yData[2]
      })
    }
    chartData.yData = series;
    this.initChart(chartData);
  },
  // 生成折线图
  initChart(chartData) {
    let that = this;
    // 绑定组件
    this.barComponent = this.selectComponent("#mychart-dom-bar");
    // 初始化折线图
    this.barComponent.init((canvas, width, height, dpr) => {
      // 初始化图表
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // 解决模糊显示问题
      })

      // 调整横坐标标签
      if (this.data.select_time == 2) { // 月
        for (let i = 0; i < chartData.xData.length; i++) {
          if (chartData.xData[i].length > 5) {
            chartData.xData[i] = chartData.xData[i].slice(5);
          }
        }
      } else if (this.data.select_time == 3) { // 年
        for (let i = 0; i < chartData.xData.length; i++) {
          if (!chartData.xData[i].endsWith('月')) {
            chartData.xData[i] = chartData.xData[i] + '月';
          }
        }
      }
      // 开发中根据从后端获取chartData数据,动态更新图表
      chart.setOption(chartsOption.barOption(chartData))
      return chart;
    })
  },
  errorNotice: function (res) {
    wx.showToast({
      title: "因数据安全考虑\r\n目前暂不开放该功能",
      icon: 'none',
      duration: 2000
    })
  },
  goToSS(){
    console.log("ss管理")
    wx.navigateTo({
      url: '/pages/ss/ssindex/ssindex'
    })
  },
  gotobook(){
    console.log("预约管理")
    wx.reLaunch({
      url: '/pages/mbook/mbook',
    })
  },
  goToAss(){
    console.log("画像评测")
    wx.reLaunch({
      url: '/pages/assess/assess',
    })
  },
  goToMyInfo(){
    console.log("我的信息")
    wx.navigateTo({
      url: '/pages/mgmyinfo/mgmyinfo'
    })
  },
  goToMmp(){
    console.log("客户明细")
    wx.reLaunch({
      url: '/pages/user/user',
    })
  },
  goToMSGSend(){
    wx.requestSubscribeMessage({
      tmplIds: ['BiP7HBKMoj24OhFZwj6LAmbuT5Kp2omjuBKqxhhTNdM','g-zexPRtyQtaAQInrkaYKIOZUgXqfiPmir-l6HSYs7g'],
      success (res) {
        
      }
    })
  },

  goToWD(){
    console.log("网点查询")
    wx.navigateTo({
      url: '/pages/wd/wdindex/wdindex'
    })
    
  }
  
})
